﻿using System;
using System.Net;
using Microsoft.Silverlight.Windows.Taskbar;
using System.Windows;
using SuperLauncher.Entitys;
using System.Collections.Generic;
using System.Runtime.InteropServices.Automation;

namespace SuperLauncher.Helpers
{
    public static class JumpListHelper
    {
        public static bool RunJumplistTask()
        {
            int launchingItemID = TaskbarButton.Current.Jumplist.LaunchingItemID;
            if (launchingItemID == -1)
            {
                return false;
            }

            DataHelper.CategoryInfos = DataHelper.ReadData();

            foreach (var category in DataHelper.CategoryInfos)
            {
                foreach (var item in category.Items)
                {
                    if (launchingItemID == item.LaunchingItemID)
                    {
                        JumpListHelper.Execute(item.Path, item.CommandLineArguments, item.StartDirectory);
                        break;
                    }
                }
            }

            return true;
        }

        public static void RefreshJumplist(ICollection<CategoryInfo> categoryInfos)
        {
            List<JumpListItem> jumpListItems = new List<JumpListItem>();
            foreach (var category in categoryInfos)
            {
                if (category.Title == DataHelper.NoCategoryName)
                {
                    continue;
                }

                foreach (var item in category.Items)
                {
                    JumpListItem jumpListItem = TaskbarButton.Current.Jumplist.CreateJumpListItem(item.LaunchingItemID);
                    jumpListItem.Category = category.Title;
                    jumpListItem.Description = item.Description;
                    jumpListItem.CommandLineArguments = item.CommandLineArguments;
                    jumpListItem.ShowCmd = ShowWindowState.SW_SHOWMINNOACTIVE;
                    jumpListItem.Title = item.Title;
                    jumpListItems.Add(jumpListItem);
                }
            }

            TaskbarButton.Current.Jumplist.SetJumpListItems(jumpListItems.ToArray());
        }

        public static void Execute(string path, string vArguments = "", string vDirectory = "", string vOperation = "open", int vShow = 1)
        {
            //MessageBox.Show(path ?? "NULL");
            //using (dynamic shell = AutomationFactory.CreateObject("WScript.Shell"))
            //{ 
            //    shell.Run(item.Path, 5, false);
            //}

            using (dynamic shell = AutomationFactory.CreateObject("Shell.Application"))
            {
                shell.ShellExecute(path, vArguments, vDirectory, vOperation, vShow);
            }
        }
    }
}
